<?php
declare (strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;

class CreateBookReadTable extends Command
{
    // 分表数量
    protected $number = 50;

    // 表前缀
    protected $tablePre = 'ziyi_book_read_';


    protected function configure()
    {
        // 指令配置
        $this->setName('create_book_read')
            ->setDescription('创建书籍阅读历史分表');
    }

    protected function execute(Input $input, Output $output)
    {
        // 连接阅读库
        $connect = Db::connect('book_read');

        // 删除表 测试使用
        // $this->dropTable($connect);

        for ($i = 0; $i < $this->number; $i++) {
            $table = $this->tablePre . $i;
            // 创建表
            $connect->execute("
            CREATE TABLE `{$table}` (
                    `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
                    `user_id` int(11) NOT NULL DEFAULT 0 COMMENT '用户ID',
                    `book_id` int(11) NOT NULL DEFAULT 0  COMMENT '书籍ID',
                    `chapter_id` int(11) NOT NULL DEFAULT 0  COMMENT '章节ID',
                    `chapter_order` int(11) NOT NULL DEFAULT 0  COMMENT '章节编号',
                    `create_time` int(11) NOT NULL DEFAULT 0  COMMENT '创建时间',
                    PRIMARY KEY (`id`)
                )DEFAULT CHARSET=utf8mb4 COMMENT='阅读历史表';
            ");

            // 添加索引
            $connect->execute("ALTER TABLE `{$table}` ADD INDEX idx_user_id(user_id);");
            $connect->execute("ALTER TABLE `{$table}` ADD INDEX idx_book_id(book_id);");
            $connect->execute("ALTER TABLE `{$table}` ADD INDEX idx_chapter_id(chapter_id);");
            $connect->execute("ALTER TABLE `{$table}` ADD INDEX idx_chapter_order(chapter_order);");
        }

        // 指令输出
        $output->writeln('创建书籍阅读历史分表完成');
    }


    protected function dropTable($connect)
    {
        for ($i = 0; $i < $this->number; $i++) {
            $table = $this->tablePre . $i;
            $connect->execute("DROP TABLE IF EXISTS {$table};");
        }
    }
}
